package com.jinzhi.jzcultivate.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

/**
 * 培训控制器
 */
@Controller
@AllArgsConstructor
@RequestMapping("/cultivate")
public class CulIndexController extends BaseController {

    @Autowired
    private ConsultationsService consultationsService;

    @Autowired
    private CoursesService coursesService;

    @Autowired
    private ExpertsService expertsService;

    @Autowired
    private UserService userService;

    @Autowired
    private LearnRecordService learnRecordService;

    @Autowired
    private OrganizationNewsService organizationNewsService;

    @Autowired
    private OrganizationRolesService organizationRolesService;

    @Autowired
    private ResumesService resumesService;

    @Autowired
    private ApplicationRecordService applicationRecordService;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private RecruitmentNewsService recruitmentNewsService;

    @Autowired
    private TrainingCertificatesService trainingCertificatesService;

    @Log("首页")
    @GetMapping("/homepage")
    String index(Model model) {
        return "cultivateWeb/index";
    }

    @Log("课程列表")
    @GetMapping("/courseIndex")
    String courseIndex() {
        return "cultivateWeb/course/courseIndex";
    }

    @Log("资讯列表")
    @GetMapping("/news")
    String news(Model model, String name) throws UnsupportedEncodingException {
        String u_name = java.net.URLDecoder.decode(name, "UTF-8");// 解码
        u_name = new String(u_name.getBytes("iso-8859-1"), "utf-8");
        model.addAttribute("name", name);
        return "cultivateWeb/news/news";
    }

    @Log("关于我们")
    @GetMapping("/about")
    String about() {
        return "cultivateWeb/about";
    }

    @Log("师资介绍")
    @GetMapping("/teacher")
    String teacher() {
        return "cultivateWeb/teach/teacher";
    }

    @Log("师资详情")
    @GetMapping("/teacherDetails")
    String teacherDetails(Model model, String id) {
        model.addAttribute("id", id);
        return "cultivateWeb/teach/teacherDetails";
    }

    @Log("信息查询")
    @GetMapping("/query")
    String query() {
        return "cultivateWeb/query/query";
    }

    @Log("机构申请页面")
    @GetMapping("/apply")
    String apply() {
        return "cultivateWeb/apply/orgApply";
    }

    @Log("创新创业")
    @GetMapping("startUpBus")
    String startUpBus() {     //培训平台登录注册
        return "cultivateWeb/teach/startUpBus";
    }

    @Log("个人中心")
    @GetMapping("my")
    String myCenter(Model model) {
        return "cultivateWeb/my/my";
    }

    @Log("编辑个人资料")
    @GetMapping("editMy")
    String editMy() {
        return "cultivateWeb/my/editMy";
    }

    @Log("登录注册")
    @GetMapping("cultivateLogins")
    String cultivateLogins(Model model, String name) throws UnsupportedEncodingException {  //培训平台登录注册
        String u_name = java.net.URLDecoder.decode(name, "UTF-8");// 解码
        u_name = new String(u_name.getBytes("iso-8859-1"), "utf-8");
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条
        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("name", name);
        model.addAttribute("consultations", consultationsDOList);
        String codeimg=null;
        try {
            //配置微信回调

           // String urlString = URLEncoder.encode("https://www.jz1x.com/jzApi/wximgCode/wxlogCodePx", "utf-8");
            String urlString = URLEncoder.encode("http://3157577pv9.eicp.vip/jzApi/wximgCode/wxlogCodePx", "utf-8");
            codeimg="https://open.weixin.qq.com/connect/qrconnect?appid=wxa5b743d1daed59cc&redirect_uri="+urlString+"&response_type=code&scope=snsapi_login&state=e97555458779708b99b9d40cb49f54245c7500e536445d32#wechat_redirect";

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        model.addAttribute("url", codeimg);
        return "cultivateWeb/login";
    }

    @Log("手机端登录")
    @GetMapping("mobileLogin")
    String mobileLogin(Model model, String name) throws UnsupportedEncodingException {  //培训平台登录注册
        String u_name = java.net.URLDecoder.decode(name, "UTF-8");// 解码
        u_name = new String(u_name.getBytes("iso-8859-1"), "utf-8");
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条
        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("name", name);
        model.addAttribute("consultations", consultationsDOList);
//        String codeimg=null;
//        try {
//            //配置微信回调
//            String urlString = URLEncoder.encode("https://www.jz1x.com/jzApi/wximgCode/wxlogCode", "utf-8");
//            codeimg="https://open.weixin.qq.com/connect/qrconnect?appid=wxa5b743d1daed59cc&redirect_uri="+urlString+"&response_type=code&scope=snsapi_login&state=e97555458779708b99b9d40cb49f54245c7500e536445d32#wechat_redirect";
//
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        model.addAttribute("url", codeimg);
        return "cultivateWeb/mobileLogin";
    }

    @Log("忘记密码页面")
    @GetMapping("forgetPass")
    String forgetPass() {  //培训平台登录注册
        return "cultivateWeb/forgetPass";
    }

    @Log("应聘就业页面")
    @GetMapping("getRecruit")
    String getRecruit() {
        return "cultivateWeb/recruit/recruit";
    }
    @Log("应聘就业页面")
    @GetMapping("recruitMobile")
    String recruitMobile() {
        return "cultivateWeb/recruit/recruitMobile";
    }
    @Log("岗位详情")
    @GetMapping("recruitInfo")
    String recruitInfo(Model model, Long id) {
        model.addAttribute("id", id);
        return "cultivateWeb/recruit/recruitInfo";
    }

    @Log("机构申请")
    @PostMapping("addOrg")
    @ResponseBody
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<Object> addOrg(@RequestHeader(value = TOKEN_TAG, required = false) String token, String name, String roleType, String orgType, String orgCode, String address,
                                    String legalRepresentative, String scopeOfBusiness, String staffSize, String staffArrangement,
                                    String profileId, String contacts, String contactsPost,
                                    String mobile, String email, String schoolNature, String url, String numberOfExaminees, String teacherResources,
                                    String province, String introduce, String industry, String orgSize, String orgPhoto,
                                    String orgItem, String trainingJobs, String trainingArrangement, Integer trainingPerson, String workPhoneNum) {

        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }

        EntityWrapper<OrganizationNewsDO> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("name", name);
        OrganizationNewsDO organizationNewsDOS = organizationNewsService.selectOne(entityWrapper);
        OrganizationNewsDO organizationNewsDO1;

        if (organizationNewsDOS != null) {
            if(!organizationNewsDOS.getCreaterId().equals(user.getId())){
                OrganizationRolesDO rolesDO = organizationRolesService.findOneByKv("org_id",organizationNewsDOS.getId());
                if(rolesDO.getCheckerState()!=4)
                    return ApiResult.fail("机构已存在！");
            }
            //3.判断机构角色表汇总是否存在该类型数据
            Map map = new HashMap();
            map.put("roleType", roleType);
            map.put("orgId", organizationNewsDOS.getId());
            Long id = organizationRolesService.selById(map);
            if (id != null) {
                //提示已申请
//				throw new IFastApiException(ApiEnumError.APPLY_ED.getCodeStr());
                return ApiResult.build(ApiEnumError.APPLY_ED.getCode(), ApiEnumError.APPLY_ED.getMsg());
            }
            organizationNewsDO1 = organizationNewsDOS;
            if (organizationNewsDO1.getOrgPhoto() == null){
                organizationNewsDO1.setOrgPhoto(orgPhoto);
                organizationNewsService.updateById(organizationNewsDO1);
            }

        } else {
            //3.新建机构实体，存入数据
            OrganizationNewsDO organizationNewsDO = new OrganizationNewsDO();
            organizationNewsDO.setName(name);//企业名称
            organizationNewsDO.setOrgCode(orgCode);//机构代码
            organizationNewsDO.setAddress(address);//单位/学校地址
            organizationNewsDO.setLegalRepresentative(legalRepresentative);//法人代表
            organizationNewsDO.setContacts(contacts);//联系人
            organizationNewsDO.setContactsPost(contactsPost);//联系人职务
            organizationNewsDO.setMobile(mobile);//联系电话
            organizationNewsDO.setMailbox(email);//电子邮箱
            organizationNewsDO.setUrl(url);//网站
            organizationNewsDO.setCreaterId(user.getId());//创建人id
            organizationNewsDO.setUpdaterId(user.getId());//更新人id
            organizationNewsDO.setLeadingCadreId(user.getId());//负责人id
            organizationNewsDO.setType(Integer.parseInt(orgType));//机构类型（0企业、1机关、2事业单位、3社会团体、4其它组织机构）
            organizationNewsDO.setProvince(province);
//			organizationNewsDO.setCachet(cachet);
            organizationNewsDO.setIntroduce(introduce);
            organizationNewsDO.setWorkPhoneNum(workPhoneNum);
            organizationNewsDO.setIndustry(industry);
            organizationNewsDO.setOrgSize(orgSize);
            organizationNewsDO.setOrgPhoto(orgPhoto);
            organizationNewsDO.setOrgItem(orgItem);
            organizationNewsDO.setTrainingJobs(trainingJobs);
            organizationNewsDO.setTrainingArrangement(trainingArrangement);
            organizationNewsDO.setTrainingPerson(trainingPerson);
            //这里只有事业单位和企业两种
            if (orgType.equals("0")) {
                organizationNewsDO.setScopeOfBusiness(scopeOfBusiness);//营业范围
                organizationNewsDO.setStaffSize(staffSize);//员工数量
                organizationNewsDO.setStaffArrangement(staffArrangement);//员工学历层次
            }
            if (orgType.equals("2")) {
                organizationNewsDO.setTeacherResources(teacherResources);//师资力量
                organizationNewsDO.setSchoolNature(Integer.parseInt(schoolNature));//学校性质(0中职,1高职,2本科)
                if (StringUtils.isNotBlank(numberOfExaminees)) {
                    organizationNewsDO.setNumberOfExaminees(Integer.parseInt(numberOfExaminees));//考生数
                } else {
                    organizationNewsDO.setNumberOfExaminees(0);//考生数
                }
            }
            boolean b = organizationNewsService.insert(organizationNewsDO);
            if (!b) {
                return ApiResult.fail();
            }
            organizationNewsDO1 = organizationNewsDO;

			/*user.setOrgId(organizationNewsDO1.getId());
			user.setOrgName(organizationNewsDO1.getName());
			userService.updateById(user);*/
        }



        OrganizationRolesDO organizationRolesDO = new OrganizationRolesDO();
        organizationRolesDO.setProfileId(profileId);//证书概况id
        organizationRolesDO.setRoleType(Integer.parseInt(roleType));//机构角色
        organizationRolesDO.setOrgId(organizationNewsDO1.getId());//机构id
        organizationRolesDO.setApplicantId(user.getId());//申请人id
        organizationRolesDO.setApplicantDate(new Date());//申请时间
//		String enclosures = "";
//		try {
//			enclosures = fileService.upload(enclosure.getBytes(), enclosure.getOriginalFilename());
//		} catch (IOException e) {
//			e.printStackTrace();
//			throw new IFastApiException(ApiEnumError.FileUploadError.getCodeStr());
//		}
        organizationRolesDO.setEnclosure(null);//机构申请附件

        boolean c = organizationRolesService.insert(organizationRolesDO);
        if (c) {
            return ApiResult.success();
        } else {
            return ApiResult.fail();
        }
    }

    @Log("跳转机构编辑")
    @GetMapping("orgEdit")
    String orgEdit(Model model, String orgId) {

		/*OrganizationRolesDO orgRole = organizationRolesService.selectById(orgId);
		if (orgRole != null){
			OrganizationNewsDO orgNews = organizationNewsService.selectById(orgRole.getOrgId());
			model.addAttribute("orgNews" , orgNews);
			model.addAttribute("orgRole" , orgRole);
		}*/
        model.addAttribute("orgId", orgId);
        return "cultivateWeb/my/orgEdit";
    }

    @Log("机构编辑查询")
    @GetMapping("orgSelInfo")
    @RequiresAuthentication
    @ResponseBody
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> orgSelInfo(@RequestHeader(value = TOKEN_TAG, required = false) String token, String orgId) {

        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }
        OrganizationRolesDO orgRole = organizationRolesService.selectById(orgId);
        OrganizationNewsDO orgNews = organizationNewsService.selectById(orgRole.getOrgId());
        orgNews.setEnclosure(orgRole.getEnclosure());
        orgNews.setRoleType(orgRole.getRoleType().toString());
        orgNews.setRoleId(orgRole.getId().toString());
        orgNews.setProfileId(orgRole.getProfileId());

        return ApiResult.success(orgNews);
    }

    @Log("机构申请时查询机构")
    @GetMapping("findOrg")
    @RequiresAuthentication
    @ResponseBody
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> findOrg(@RequestHeader(value = TOKEN_TAG, required = false) String token, String orgId) {

        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }
        OrganizationNewsDO org = organizationNewsService.selectById(orgId);

        return ApiResult.success(org);
    }


    @Log("提交机构编辑")
    @PostMapping("/saveOrg")
    @ResponseBody
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> saveOrg(@RequestHeader(value = TOKEN_TAG, required = false) String token, String name, String roleType, String orgType, String orgCode, String address,
                                String legalRepresentative, String scopeOfBusiness, String staffSize, String staffArrangement,
                                String profileId, String contacts, String contactsPost,
                                String mobile, String email, String schoolNature, String url, String numberOfExaminees, String teacherResources,
                                String enclosure, String province, String introduce, String industry, String orgSize, String orgPhoto,
                                String orgItem, String trainingJobs, String trainingArrangement, Integer trainingPerson, String orgRoleId) {

        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }


        OrganizationRolesDO organizationRolesDO = organizationRolesService.selectById(orgRoleId);

        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(organizationRolesDO.getOrgId());
        organizationNewsDO.setName(name);//企业名称
        organizationNewsDO.setOrgCode(orgCode);//机构代码
        organizationNewsDO.setAddress(address);//单位/学校地址
        organizationNewsDO.setLegalRepresentative(legalRepresentative);//法人代表
        organizationNewsDO.setContacts(contacts);//联系人
        organizationNewsDO.setContactsPost(contactsPost);//联系人职务
        organizationNewsDO.setMobile(mobile);//联系电话
        organizationNewsDO.setMailbox(email);//电子邮箱
        organizationNewsDO.setOrgPhoto(orgPhoto);
        organizationNewsDO.setProvince(province);
        organizationNewsDO.setUrl(url);//网站
        organizationNewsDO.setOrgItem(orgItem);
        organizationNewsDO.setIndustry(industry);
        organizationNewsDO.setOrgSize(orgSize);
        organizationNewsDO.setTrainingPerson(trainingPerson);
        organizationNewsDO.setTrainingArrangement(trainingArrangement);
        organizationNewsDO.setTrainingJobs(trainingJobs);
        organizationNewsDO.setUpdaterId(user.getId());//更新人id
        organizationNewsDO.setLeadingCadreId(user.getId());//负责人id
        organizationNewsDO.setType(Integer.parseInt(orgType));//机构类型（0企业、1机关、2事业单位、3社会团体、4其它组织机构）
        organizationNewsDO.setUpdateDate(new Date());
        organizationNewsDO.setIntroduce(introduce);

        //这里只有事业单位和企业两种
        if (orgType.equals("0")) {
            organizationNewsDO.setScopeOfBusiness(scopeOfBusiness);//营业范围
            organizationNewsDO.setStaffSize(staffSize);//员工数量
            organizationNewsDO.setStaffArrangement(staffArrangement);//员工学历层次
        }
        if (orgType.equals("2")) {
            organizationNewsDO.setTeacherResources(teacherResources);//师资力量
            organizationNewsDO.setSchoolNature(Integer.parseInt(schoolNature));//学校性质(0中职,1高职,2本科)
            if (StringUtils.isNotBlank(numberOfExaminees)) {
                organizationNewsDO.setNumberOfExaminees(Integer.parseInt(numberOfExaminees));//考生数
            } else {
                organizationNewsDO.setNumberOfExaminees(0);//考生数
            }
        }
        boolean b = organizationNewsService.updateById(organizationNewsDO);
        if (!b) {
            return ApiResult.fail();
        }

        organizationRolesDO.setProfileId(profileId);//证书概况id
        organizationRolesDO.setRoleType(Integer.parseInt(roleType));//机构角色
        organizationRolesDO.setOrgId(organizationNewsDO.getId());//机构id
        organizationRolesDO.setApplicantId(user.getId());//申请人id
        organizationRolesDO.setApplicantDate(new Date());//申请时间
        organizationRolesDO.setEnclosure(enclosure);//机构申请附件
        organizationRolesDO.setCheckerState(0);

        boolean c = organizationRolesService.updateById(organizationRolesDO);
        if (c) {
            return ApiResult.success();
        } else {
            return ApiResult.fail();
        }
    }

    @Log("申请记录")
    @GetMapping("applyRecord")
    String applyRecord() {
        return "cultivateWeb/my/applyRecord";
    }

    @Log("我的课程")
    @GetMapping("myCourse")
    String myCourse(Model model) {
        return "cultivateWeb/my/myCourse";
    }

    @Log("我的课程")
    @GetMapping("myCoursePlan")
    String myCoursePlan(Model model) {
        return "cultivateWeb/my/myCoursePlan";
    }

    @Log("我的简历")
    @GetMapping("myResume")
    String myResume(Model model) {
        return "cultivateWeb/my/myResume";
    }
    @Log("移动版我的简历")
    @GetMapping("myResumes")
    String myResumes(Model model) {
        return "cultivateWeb/my/myResumes";
    }
    @Log("跳转简历")
    @GetMapping("addResume")
    String addResume(Model model) {
        return "cultivateWeb/my/addResume";
    }
    @Log("移动版添加简历")
    @GetMapping("addResumes")
    String addResumes(Model model) {
        return "cultivateWeb/my/addResumes";
    }
    @Log("跳转简历")
    @GetMapping("editResume")
    String editResume(Model model) {
        return "cultivateWeb/my/editResume";
    }
    @Log("移动版编辑简历")
    @GetMapping("editResumes")
    String editResumes(Model model) {
        return "cultivateWeb/my/editResumes";
    }

    @Log("我的订单")
    @GetMapping("myOrder")
    String myOrder() {
        return "cultivateWeb/my/orderRecord";
    }


    @Log("不推荐就业")
    @GetMapping("unRecommend")
    String unRecommend() {
        return "cultivateWeb/my/unRecommend";
    }



    @Log("投递记录")
    @GetMapping("deliverRecord")
    String deliverRecord() {
        return "cultivateWeb/my/deliverRecord";
    }

    @Log("学习记录")
    @GetMapping("studyRecord")
    String studyRecord() {
        return "cultivateWeb/my/studyRecord";
    }

    @Log("消息中心")
    @GetMapping("/myMessage")
    String myMessage() {
        return "cultivateWeb/my/message";
    }

    @GetMapping("/recruitApply")
    @Log("岗位申请")
    @ResponseBody
    @RequiresAuthentication
    public Result<?> recruitApply(String id) {

        UserDO user = userService.selectById(getUserId());

        RecruitmentNewsDO recruitmentNewsDO = recruitmentNewsService.selectById(Long.parseLong(id));
        if (recruitmentNewsDO != null) {
            ApplicationRecordDO applicationRecordDO = applicationRecordService.findOneByKv("user_id", user.getId(), "rnews_id", Long.parseLong(id));
            if (applicationRecordDO == null) {
                ApplicationRecordDO applicationRecordDO1 = new ApplicationRecordDO();
                applicationRecordDO1.setUserId(user.getId());//用户id
                applicationRecordDO1.setOrgId(recruitmentNewsDO.getOrgId());//机构id
                applicationRecordDO1.setRnewsId(Long.parseLong(id));//招聘岗位id
                applicationRecordDO1.setAppTime(new Date());//应聘时间
                applicationRecordDO1.setCreaterDate(new Date());//创建时间
                applicationRecordDO1.setState(2);//默认沟通中
                boolean b = applicationRecordService.insert(applicationRecordDO1);
                if (b) {
                    recruitmentNewsDO.setAppNumber(recruitmentNewsDO.getAppNumber() + 1);
                    recruitmentNewsService.updateById(recruitmentNewsDO);

                    return Result.ok("投递成功，请静候佳音！");
                } else {
                    return Result.fail("投递失败，请刷新重试！");
                }
            } else {
                return Result.fail("您已投递，请勿重复！");
            }
        } else {
            return Result.fail("信息错误，请刷新重试！");
        }
    }

    @Log("我的证书")
    @GetMapping("/myCertificates")
    String myCertificates() {
        return "cultivateWeb/my/myCertificates";
    }

}
